<template>
    <a-transfer class="i-transfer-tree" :listStyle="listStyle"  :data-source="dataSource" :target-keys="targetKeys"
      :render="item => item.title" @change="onChange" v-bind="transferData.options">
      <template #children="{ direction, selectedKeys, onItemSelect }">
        <a-tree v-if="direction === 'left'" blockNode checkable checkStrictly defaultExpandAll v-bind="transferData.treeOptions"
          :checkedKeys="[...selectedKeys, ...targetKeys]" :treeData="treeData" @check="
            (_, props) => {
              onChecked(_, props, [...selectedKeys, ...targetKeys], onItemSelect);
            }
          " @select="
            (_, props) => {
              onChecked(_, props, [...selectedKeys, ...targetKeys], onItemSelect);
            }
          " />
      </template>
    </a-transfer>
</template>
<script lang="ts">
// import { CheckEvent } from 'ant-design-vue/es/tree/Tree'
import { computed, defineComponent, PropType, ref, watch } from 'vue'
import { TransferTreeDataInterface } from './ITransferTreeInterFace'
interface TreeDataItem {
  key: string;
  title: string;
  disabled?: boolean;
  children?: TreeDataItem[];
  [index: string]: any;
}
function isChecked (selectedKeys: string[], eventKey: string) {
  return selectedKeys.indexOf(eventKey) !== -1
}
function handleTreeData (
  data: TreeDataItem[],
  targetKeys: string[] = []
): TreeDataItem[] {
  data.forEach((item) => {
    item.disabled = targetKeys.includes(item.key)
    if (item.children) {
      handleTreeData(item.children, targetKeys)
    }
  })
  return data
}
export default defineComponent({
  props: {
    transferTreeData: {
      type: Object as PropType<TransferTreeDataInterface<any>>,
      required: true
    }
  },
  setup (props, ctx) {
    const listStyle = ref({
      height: '100%',
      width: '50%',
      overflow: 'hidden auto'
    })
    // const halfCheckedList = ref<string[]>([])
    // ref调取获取选中
    const checkTransferDataList = () => {
      return targetKeys.value
    }
    const dataSource = ref<any[]>([])
    const transferData = ref<TransferTreeDataInterface<any>>({
      dataList: [],
      checkList: []
    })
    // 过滤
    const filterField = ref<string>(
      props.transferTreeData.filterField ? props.transferTreeData.filterField : 'title'
    )
    const targetKeys = ref<string[]>([])
    const treeData = computed<TreeDataItem[]>(() => {
      return handleTreeData(transferData.value.dataList, targetKeys.value)
    })
    const getTargetKeysTreeData = (dataList: any[], key = '', valueData:any) => {
      for (let i = 0; i < dataList.length; i++) {
        if (dataList[i].key === key) {
          valueData = JSON.parse(JSON.stringify(dataList[i]))
          return true
        } else if (dataList[i].children) {
          const flg = getTargetKeysTreeData(dataList[i].children, key, valueData)
          if (flg === true) {
            return true
          }
        }
      }
    }
    const onChange = (keys: string[], direction:string, extendList:string[]) => {
      if (transferData.value.treeOptions && transferData.value.treeOptions.checkStrictly === false) {
        if (direction === 'right') {
          if (keys.length > 0) {
            const dataList:string[] = []
            // halfCheckedList.value.forEach(item => {
            //   if (!keys.some(sitem => sitem === item)) {
            //     ts.push(item)
            //     const data = dataSource.value.find(source => source.key === sitem)
            //   }
            // })
            keys.forEach(item => {
              const data = dataSource.value.find(source => source.key === item)
              dataList.push(item)
              if (data.parentIdList) {
                data.parentIdList.forEach((sitem:string) => dataList.push(sitem))
              }
            })
            targetKeys.value = dataList
          } else {
            targetKeys.value = []
          }
        }
        if (direction === 'left') {
          const dataList = transferData.value.dataList.filter(item => extendList.find(sitem => sitem === item.key))
          if (dataList.length > 0) {
            dataList.forEach(item => {
              item.children && item.children.forEach((sitem:any) => extendList.push(sitem.key))
            })
          }
          targetKeys.value = targetKeys.value.filter((item) => !extendList.some((sitem) => sitem === item))
        }
      } else {
        targetKeys.value = keys
      }
      // 选项发生改变后回调方法
      ctx.emit('chagneTreeDataFun', targetKeys.value)
    }
    const onClear = () => {
      targetKeys.value = []
      dataSource.value = []
      //   halfCheckedList.value = []
      transferData.value = {
        dataList: [],
        checkList: []
      }
    }
    const onChecked = (
      _: Record<string, string[]>,
      e: any,
      checkedKeys: string[],
      onItemSelect: (n: any, c: boolean) => void
    ) => {
      const { eventKey } = e.node
      //   halfCheckedList.value = []
      //   e.halfCheckedKeys && e.halfCheckedKeys.forEach(item => halfCheckedList.value.push(item.toString()))
      //   e.checkedNodes && e.checkedNodes.forEach(item => halfCheckedList.value.push(item.key))
      onItemSelect(eventKey, !isChecked(checkedKeys, eventKey))
    }
    const getTreeData = (treedList: any) => {
      return treedList.map((item: any) => {
        const data = {
          ...item,
          title: item[props.transferTreeData.fileNames?.title || 'title'],
          key: item[props.transferTreeData.fileNames?.key || 'key'],
          disabled:
            item[props.transferTreeData.fileNames?.disabled || 'disabled'],
          description:
            item[
              props.transferTreeData.fileNames?.description || 'description'
            ],
          children:
            item[
              props.transferTreeData.fileNames?.children || 'children'
            ]
        }
        if (item.children) {
          data.children = getTreeData(item.children)
        }
        dataSource.value.push(JSON.parse(JSON.stringify(data)))
        return data
      })
    }
    watch(
      props.transferTreeData,
      () => {
        onClear()
        dataSource.value = []
        transferData.value = JSON.parse(JSON.stringify(props.transferTreeData))
        transferData.value.dataList = getTreeData(
          props.transferTreeData.dataList
        )
        targetKeys.value = JSON.parse(
          JSON.stringify(props.transferTreeData)
        ).checkList
      },
      {
        deep: true
      }
    )
    return {
      onClear,
      //   halfCheckedList,
      checkTransferDataList,
      listStyle,
      transferData,
      targetKeys,
      dataSource,
      treeData,
      filterField,
      onChange,
      onChecked
    }
  }
})
</script>
